<template>
  <div class="results-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1>录取名单</h1>
        <p class="subtitle">提前招生录取结果查询与公示</p>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="container">
      <div class="main-content">
        <!-- 个人查询 -->
        <el-card class="query-card" shadow="hover">
          <template #header>
            <h2><el-icon><Search /></el-icon> 个人录取结果查询</h2>
          </template>
          
          <el-form 
            ref="queryFormRef"
            :model="queryForm" 
            :rules="queryRules" 
            label-width="120px"
            size="large"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input 
                    v-model="queryForm.idCard" 
                    placeholder="请输入身份证号"
                    maxlength="18"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="studentName">
                  <el-input 
                    v-model="queryForm.studentName" 
                    placeholder="请输入姓名"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                :loading="querying"
                @click="queryResult"
              >
                {{ querying ? '查询中...' : '查询录取结果' }}
              </el-button>
              <el-button size="large" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 个人查询结果 -->
          <div v-if="personalResult" class="personal-result">
            <el-divider content-position="left">录取结果</el-divider>
            <div class="result-content">
              <div class="result-header">
                <el-tag 
                  :type="getAdmissionStatusType(personalResult.admissionStatus)"
                  size="large"
                  class="status-tag"
                >
                  {{ getAdmissionStatusText(personalResult.admissionStatus) }}
                </el-tag>
                <h3 v-if="personalResult.admissionStatus === 'admitted'" class="congratulations">
                  🎉 恭喜您被录取！
                </h3>
                <h3 v-else-if="personalResult.admissionStatus === 'waitlist'" class="waitlist">
                  候补中，请耐心等待
                </h3>
                <h3 v-else class="rejected">
                  很遗憾，未被录取
                </h3>
              </div>

              <div class="result-details">
                <div class="detail-grid">
                  <div class="detail-item">
                    <span class="label">姓名：</span>
                    <span class="value">{{ personalResult.studentName }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">身份证号：</span>
                    <span class="value">{{ maskIdCard(personalResult.idCard) }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">录取院校：</span>
                    <span class="value">{{ personalResult.schoolName }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">录取专业：</span>
                    <span class="value">{{ personalResult.majorName }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">高考总分：</span>
                    <span class="value">{{ personalResult.totalScore }}分</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">校测成绩：</span>
                    <span class="value">{{ personalResult.examScore }}分</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">最终成绩：</span>
                    <span class="value">{{ personalResult.finalScore }}分</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">专业排名：</span>
                    <span class="value">第{{ personalResult.rankInMajor }}名</span>
                  </div>
                  <div v-if="personalResult.publishTime" class="detail-item">
                    <span class="label">发布时间：</span>
                    <span class="value">{{ personalResult.publishTime }}</span>
                  </div>
                </div>

                <!-- 下一步操作 -->
                <div v-if="personalResult.admissionStatus === 'admitted'" class="next-actions">
                  <h4>后续事项</h4>
                  <div class="actions-content">
                    <p>请及时关注录取通知书邮寄信息，并按照院校要求完成入学报到手续。</p>
                    <div class="action-buttons">
                      <el-button type="primary" @click="downloadAdmissionLetter">
                        下载录取通知书
                      </el-button>
                      <el-button @click="viewEnrollmentGuide">
                        查看入学指南
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 录取名单筛选 -->
        <el-card class="filter-card" shadow="hover">
          <template #header>
            <h2><el-icon><List /></el-icon> 录取名单公示</h2>
          </template>
          
          <el-form :model="searchForm" :inline="true" label-width="80px">
            <el-form-item label="院校">
              <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
                <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="专业">
              <el-select v-model="searchForm.majorId" placeholder="选择专业" clearable>
                <el-option v-for="major in majors" :key="major.id" :label="major.name" :value="major.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="录取状态">
              <el-select v-model="searchForm.admissionStatus" placeholder="录取状态" clearable>
                <el-option label="录取" value="admitted" />
                <el-option label="候补" value="waitlist" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadResults">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 录取名单列表 -->
        <el-card v-loading="loading" class="results-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>录取名单</span>
              <div class="header-actions">
                <el-button type="primary" @click="exportResults">
                  导出名单
                </el-button>
              </div>
            </div>
          </template>

          <el-table :data="results" stripe>
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="studentName" label="姓名" width="120" />
            <el-table-column prop="idCard" label="身份证号" width="160">
              <template #default="{ row }">
                {{ maskIdCard(row.idCard) }}
              </template>
            </el-table-column>
            <el-table-column prop="schoolName" label="录取院校" />
            <el-table-column prop="majorName" label="录取专业" />
            <el-table-column prop="totalScore" label="高考总分" width="100" sortable />
            <el-table-column prop="examScore" label="校测成绩" width="100" sortable />
            <el-table-column prop="finalScore" label="最终成绩" width="100" sortable />
            <el-table-column prop="rankInMajor" label="专业排名" width="100" sortable />
            <el-table-column prop="admissionStatus" label="录取状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getAdmissionStatusType(row.admissionStatus)">
                  {{ getAdmissionStatusText(row.admissionStatus) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div v-if="pagination.total > 0" class="pagination-wrapper">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[20, 50, 100, 200]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="loadResults"
              @current-change="loadResults"
            />
          </div>
        </el-card>

        <!-- 录取统计 -->
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <h2><el-icon><DataAnalysis /></el-icon> 录取统计</h2>
          </template>
          
          <div class="stats-content">
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-value">{{ stats.totalAdmitted }}</div>
                <div class="stat-label">录取总数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.totalWaitlist }}</div>
                <div class="stat-label">候补人数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.totalApplications }}</div>
                <div class="stat-label">报名总数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.admissionRate }}%</div>
                <div class="stat-label">录取率</div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 重要提示 -->
        <el-card class="notice-card" shadow="hover">
          <template #header>
            <h2><el-icon><Warning /></el-icon> 重要提示</h2>
          </template>
          <div class="notice-content">
            <ol>
              <li>录取名单将在校测结束后统一公布，请耐心等待</li>
              <li>录取结果以正式录取通知书为准，网站查询结果仅供参考</li>
              <li>被录取的考生请按时办理入学报到手续</li>
              <li>候补考生请保持手机畅通，等待进一步通知</li>
              <li>如对录取结果有异议，请及时联系相关院校招生办公室</li>
              <li>录取通知书将通过邮政EMS寄送到考生填写的通讯地址</li>
            </ol>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, List, DataAnalysis, Warning } from '@element-plus/icons-vue'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const querying = ref(false)
const results = ref([])
const personalResult = ref(null)
const schools = ref([])
const majors = ref([])

const queryFormRef = ref()
const queryForm = reactive({
  idCard: '',
  studentName: ''
})

const searchForm = reactive({
  schoolId: '',
  majorId: '',
  admissionStatus: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const stats = reactive({
  totalAdmitted: 0,
  totalWaitlist: 0,
  totalApplications: 0,
  admissionRate: 0
})

// 表单验证规则
const queryRules = {
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  studentName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

// 方法
const queryResult = async () => {
  try {
    await queryFormRef.value.validate()
    querying.value = true
    
    const { data } = await api.get('/admission/result/query', {
      params: {
        idCard: queryForm.idCard,
        studentName: queryForm.studentName
      }
    })
    
    personalResult.value = data
    
    if (data) {
      ElMessage.success('查询成功')
    } else {
      ElMessage.warning('未查询到录取信息')
    }
  } catch (error) {
    ElMessage.error('查询失败，请稍后重试')
    personalResult.value = null
  } finally {
    querying.value = false
  }
}

const resetQuery = () => {
  Object.assign(queryForm, {
    idCard: '',
    studentName: ''
  })
  personalResult.value = null
  queryFormRef.value?.clearValidate()
}

const loadResults = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    const { data } = await api.get('/admission/result/public', { params })
    results.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('加载录取名单失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const { data } = await api.get('/schools')
    schools.value = data.records || []
  } catch (error) {
    console.error('加载院校失败:', error)
  }
}

const loadMajors = async () => {
  if (searchForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: searchForm.schoolId } 
      })
      majors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    majors.value = []
  }
}

const loadStats = async () => {
  try {
    const { data } = await api.get('/admission/result/stats')
    Object.assign(stats, data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    schoolId: '',
    majorId: '',
    admissionStatus: ''
  })
  majors.value = []
  loadResults()
}

const exportResults = () => {
  ElMessage.success('录取名单导出成功')
}

const downloadAdmissionLetter = () => {
  ElMessage.success('录取通知书下载成功')
}

const viewEnrollmentGuide = () => {
  ElMessage.info('入学指南功能开发中')
}

const maskIdCard = (idCard) => {
  if (!idCard) return ''
  return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
}

const getAdmissionStatusType = (status) => {
  const statusMap = {
    admitted: 'success',
    waitlist: 'warning',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getAdmissionStatusText = (status) => {
  const statusMap = {
    admitted: '录取',
    waitlist: '候补',
    rejected: '未录取'
  }
  return statusMap[status] || status
}

// 监听
watch(() => searchForm.schoolId, () => {
  searchForm.majorId = ''
  loadMajors()
})

// 初始化
onMounted(() => {
  loadResults()
  loadSchools()
  loadStats()
})
</script>

<style lang="scss" scoped>
.results-page {
  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 60px 0;
    text-align: center;
    
    h1 {
      font-size: 2.5rem;
      margin-bottom: 16px;
      font-weight: 600;
    }
    
    .subtitle {
      font-size: 1.2rem;
      opacity: 0.9;
    }
  }
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .main-content {
    margin-top: -40px;
    position: relative;
    z-index: 1;
    
    .el-card {
      margin-bottom: 30px;
      border-radius: 12px;
      
      .el-card__header {
        background: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        
        h2 {
          margin: 0;
          color: #495057;
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }
  }
  
  .personal-result {
    margin-top: 24px;
    
    .result-content {
      .result-header {
        text-align: center;
        margin-bottom: 24px;
        
        .status-tag {
          font-size: 18px;
          padding: 12px 24px;
          margin-bottom: 16px;
        }
        
        h3 {
          margin: 0;
          font-size: 20px;
          
          &.congratulations {
            color: #67c23a;
          }
          
          &.waitlist {
            color: #e6a23c;
          }
          
          &.rejected {
            color: #f56c6c;
          }
        }
      }
      
      .result-details {
        .detail-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
          gap: 16px;
          margin-bottom: 24px;
          
          .detail-item {
            display: flex;
            align-items: center;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 8px;
            
            .label {
              font-weight: 600;
              color: #606266;
              min-width: 100px;
            }
            
            .value {
              color: #303133;
              font-weight: 500;
            }
          }
        }
        
        .next-actions {
          background: #f0f9ff;
          border: 1px solid #b3d8ff;
          border-radius: 8px;
          padding: 20px;
          
          h4 {
            margin: 0 0 12px 0;
            color: #409eff;
          }
          
          .actions-content {
            p {
              margin: 0 0 16px 0;
              color: #606266;
              line-height: 1.6;
            }
            
            .action-buttons {
              .el-button {
                margin-right: 12px;
              }
            }
          }
        }
      }
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 24px;
    text-align: center;
  }
  
  .stats-content {
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 24px;
      
      .stat-item {
        text-align: center;
        padding: 24px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        
        .stat-value {
          font-size: 2.5rem;
          font-weight: 600;
          margin-bottom: 8px;
        }
        
        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }
      }
    }
  }
  
  .notice-content {
    ol {
      padding-left: 20px;
      
      li {
        margin-bottom: 12px;
        line-height: 1.6;
        color: #6c757d;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .results-page {
    .page-header {
      padding: 40px 0;
      
      h1 {
        font-size: 2rem;
      }
      
      .subtitle {
        font-size: 1rem;
      }
    }
    
    .detail-grid {
      grid-template-columns: 1fr !important;
    }
    
    .stats-grid {
      grid-template-columns: repeat(2, 1fr) !important;
    }
    
    .next-actions .action-buttons {
      .el-button {
        display: block;
        width: 100%;
        margin: 0 0 8px 0;
      }
    }
  }
}
</style>